import { InventoryItem, ItemConfig, ItemRarity } from '../types/game';
import { ALL_ITEMS } from '../data/itemConfigs';

/**
 * 物品管理工具类
 */
export class ItemManager {
  /**
   * 根据物品ID获取物品配置
   */
  static getItemConfig(itemId: string): ItemConfig | null {
    return ALL_ITEMS[itemId] || null;
  }

  /**
   * 创建物品实例
   */
  static createItem(itemId: string, quantity: number = 1, enhancement: number = 0): InventoryItem | null {
    const config = this.getItemConfig(itemId);
    if (!config) {
      console.error(`Item config not found for ID: ${itemId}`);
      return null;
    }

    // 确保数量不超过最大堆叠数
    const finalQuantity = config.stackable ? Math.min(quantity, config.maxStack) : 1;

    return {
      ...config,
      quantity: finalQuantity,
      instanceId: this.generateInstanceId(),
      enhancement,
      durability: 100 // 默认耐久度为100%
    };
  }

  /**
   * 生成唯一实例ID
   */
  private static generateInstanceId(): string {
    return `item_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
  }

  /**
   * 获取物品的实际价值（考虑强化等级）
   */
  static getItemValue(item: InventoryItem): number {
    let value = item.baseValue;
    
    // 强化等级影响价值
    if (item.enhancement && item.enhancement > 0) {
      value *= (1 + item.enhancement * 0.2); // 每级强化增加20%价值
    }

    // 稀有度影响价值
    const rarityMultiplier = this.getRarityMultiplier(item.rarity);
    value *= rarityMultiplier;

    return Math.floor(value);
  }

  /**
   * 获取稀有度价值倍数
   */
  private static getRarityMultiplier(rarity: ItemRarity): number {
    switch (rarity) {
      case ItemRarity.COMMON: return 1;
      case ItemRarity.UNCOMMON: return 1.5;
      case ItemRarity.RARE: return 3;
      case ItemRarity.EPIC: return 6;
      case ItemRarity.LEGENDARY: return 15;
      default: return 1;
    }
  }

  /**
   * 获取稀有度颜色
   */
  static getRarityColor(rarity: ItemRarity): string {
    switch (rarity) {
      case ItemRarity.COMMON: return '#2ecc71'; // 绿色
      case ItemRarity.UNCOMMON: return '#3498db'; // 蓝色
      case ItemRarity.RARE: return '#9b59b6'; // 紫色
      case ItemRarity.EPIC: return '#f39c12'; // 金色
      case ItemRarity.LEGENDARY: return '#e74c3c'; // 红色
      default: return '#95a5a6'; // 灰色
    }
  }

  /**
   * 获取稀有度显示名称
   */
  static getRarityName(rarity: ItemRarity): string {
    switch (rarity) {
      case ItemRarity.COMMON: return '普通';
      case ItemRarity.UNCOMMON: return '优秀';
      case ItemRarity.RARE: return '稀有';
      case ItemRarity.EPIC: return '史诗';
      case ItemRarity.LEGENDARY: return '传说';
      default: return '未知';
    }
  }

  /**
   * 获取物品类型显示名称
   */
  static getTypeDisplayName(type: string): string {
    const typeMap: Record<string, string> = {
      weapon: '武器',
      armor: '防具',
      consumable: '消耗品',
      key: '钥匙',
      misc: '杂物',
      equipment: '装备'
    };
    return typeMap[type] || '未知';
  }

  /**
   * 按稀有度和类型筛选物品
   */
  static getItemsByFilter(rarity?: ItemRarity, type?: string): ItemConfig[] {
    return Object.values(ALL_ITEMS).filter(item => {
      if (rarity && item.rarity !== rarity) return false;
      if (type && item.type !== type) return false;
      return true;
    });
  }

  /**
   * 获取所有武器
   */
  static getAllWeapons(): ItemConfig[] {
    return this.getItemsByFilter(undefined, 'weapon');
  }

  /**
   * 获取所有防具
   */
  static getAllArmors(): ItemConfig[] {
    return this.getItemsByFilter(undefined, 'armor');
  }

  /**
   * 获取所有消耗品
   */
  static getAllConsumables(): ItemConfig[] {
    return this.getItemsByFilter(undefined, 'consumable');
  }

  /**
   * 获取指定稀有度的物品
   */
  static getItemsByRarity(rarity: ItemRarity): ItemConfig[] {
    return this.getItemsByFilter(rarity);
  }

  /**
   * 随机获取一个指定稀有度的物品
   */
  static getRandomItemByRarity(rarity: ItemRarity): ItemConfig | null {
    const items = this.getItemsByRarity(rarity);
    if (items.length === 0) return null;
    
    const randomIndex = Math.floor(Math.random() * items.length);
    return items[randomIndex];
  }

  /**
   * 按权重随机获取物品（稀有度越高，获得概率越低）
   */
  static getRandomItem(): ItemConfig {
    const weights = {
      [ItemRarity.COMMON]: 50,     // 50%
      [ItemRarity.UNCOMMON]: 30,   // 30%
      [ItemRarity.RARE]: 15,       // 15%
      [ItemRarity.EPIC]: 4,        // 4%
      [ItemRarity.LEGENDARY]: 1    // 1%
    };

    const totalWeight = Object.values(weights).reduce((sum, weight) => sum + weight, 0);
    let random = Math.random() * totalWeight;

    for (const [rarity, weight] of Object.entries(weights)) {
      random -= weight;
      if (random <= 0) {
        const item = this.getRandomItemByRarity(rarity as ItemRarity);
        if (item) return item;
      }
    }

    // 备用：返回第一个普通物品
    return Object.values(ALL_ITEMS)[0];
  }

  /**
   * 检查两个物品是否可以合并（用于堆叠）
   */
  static canStackItems(item1: InventoryItem, item2: InventoryItem): boolean {
    return (
      item1.id === item2.id &&
      item1.stackable &&
      item2.stackable &&
      item1.enhancement === item2.enhancement
    );
  }

  /**
   * 合并物品堆叠
   */
  static stackItems(item1: InventoryItem, item2: InventoryItem): InventoryItem | null {
    if (!this.canStackItems(item1, item2)) return null;

    const totalQuantity = item1.quantity + item2.quantity;
    const maxStack = item1.maxStack;

    return {
      ...item1,
      quantity: Math.min(totalQuantity, maxStack)
    };
  }

  /**
   * 获取物品的完整显示名称（包含强化等级）
   */
  static getItemDisplayName(item: InventoryItem): string {
    let name = item.name;
    
    if (item.enhancement && item.enhancement > 0) {
      name = `+${item.enhancement} ${name}`;
    }

    return name;
  }

  /**
   * 获取物品的详细描述
   */
  static getItemDetailDescription(item: InventoryItem): string {
    let description = item.description;

    if (item.effects && item.effects.length > 0) {
      description += '\n\n效果：';
      item.effects.forEach(effect => {
        description += `\n• ${effect.description}`;
        if (effect.duration) {
          description += ` (持续${Math.floor(effect.duration / 60000)}分钟)`;
        }
      });
    }

    if (item.enhancement && item.enhancement > 0) {
      description += `\n\n强化等级：+${item.enhancement}`;
    }

    if (item.durability && item.durability < 100) {
      description += `\n耐久度：${item.durability}%`;
    }

    return description;
  }
}

// 导出一些常用的工具函数
export const {
  createItem,
  getItemConfig,
  getItemValue,
  getRarityColor,
  getRarityName,
  getTypeDisplayName,
  getRandomItem,
  getItemDisplayName,
  getItemDetailDescription
} = ItemManager;